package com.lh.ssm.util;

import com.lh.ssm.domain.User;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.util.Base64Utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * @Author: 一一哥
 * @Blame: yyg
 * @Since: Created in 2020/8/26
 * @Description: $cursor$
 */
public class MailUtils {

    /**
     * 发送邮件
     */
    public static void sendMail(User user) {
        //1.设置服务器的配置信息
        //发件人账号
        final String account = "306950684@qq.com";
        //授权码
        final String myPass = "zsqiixcqisvybjdc";
        //对会话进行设置
        Properties props = new Properties();
        //设置邮件发送协议,一般都采用smtp协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置邮件服务器
        props.setProperty("mail.host", "smtp.qq.com");
        //是否开启smtp的认证功能
        props.setProperty("mail.smtp.auth", "true");
        //是否开启ssl加密功能
        props.setProperty("mail.smtp.ssl.enable", "true");

        try {
            //设置socket连接工厂
            MailSSLSocketFactory factory = new MailSSLSocketFactory();
            //设置服务器是否是一个可以被信任的机器
            factory.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", factory);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        //2.建立会话
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            //进行与126/163/qq等邮件服务器之间的认证
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发件人邮箱账号.注意:此处的密码不是邮箱密码,而是一个授权码!
                return new PasswordAuthentication(account, myPass);
            }
        });

        //开发阶段:可以设置为debug模式,会在控制台打印邮件发送信息
        session.setDebug(true);

        try {
            //3.获取一个传输端口
            Transport transport = session.getTransport();

            //4.注意:此处必须明确的连接一下服务器!否则会产生not_connected异常!
            transport.connect(account,myPass);

            //5.创建Message对象
            MimeMessage message = createMsg(session, account, user);

            //6.利用传输端口发送邮件
            transport.sendMessage(message, message.getAllRecipients());

            //7.关闭传输端口
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建Message消息
     */
    private static MimeMessage createMsg(Session session, String account, User user)  {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);

        try {
            //设置发件人
            message.setFrom(new InternetAddress(account, "小米商城", "UTF-8"));

            //设置收件人地址
            //message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(user.getEmail(), user.getUsername(), "UTF-8")});
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail(), user.getUsername(), "UTF-8"));

            //设置邮件的主题
            message.setSubject("小米商城账号激活邮件", "UTF-8");

            //设置邮件内容
            //获取本机的ip地址
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            String url = "http://" + hostAddress + ":8080/user/active?method=active&c=" + user.getCode();
            message.setContent(user.getUsername() + ",你好! <br>欢迎注册MyShop商城! 请点击链接进行激活:<a href='" + url + "'>点击此处</a>", "text/html;charset=utf-8");

            //设置邮件发送时间
            message.setSentDate(new Date());

            //保存设置
            message.saveChanges();
        } catch (MessagingException | UnsupportedEncodingException | UnknownHostException e) {
            e.printStackTrace();
        }

        return message;
    }

}
